﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Web.Helper;
using Web.Services;
using Web.Models;

namespace Web.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            SaudoContext context = SaudoContext.Default();
            List<SaudoPlus> saudos = new List<SaudoPlus>();

            var selection = (from s in context.Saudos
                            where s.Day.Equals(DateTime.UtcNow.Date)
                            select s).AsEnumerable();

            foreach (var saudo in selection.OrderByDescending((s) => (s.Votes)))
            {
                SaudoPlus plus = new SaudoPlus()
                {
                    RowKey = saudo.RowKey,
                    PartitionKey = saudo.PartitionKey,
                    Sender = saudo.Sender,
                    Text = saudo.Text,
                    Votes = saudo.Votes,
                    Comments = context.Comments.Where((c) => (c.PartitionKey == saudo.RowKey)).AsEnumerable().Count(),
                };
                saudos.Add(plus);
            }

            return View(saudos);
        }

        public ActionResult Vote(string key)
        {
            SaudoLogic logic = new SaudoLogic();
            logic.VoteSaudo(key);
            return Redirect("/Home/Index");
        }

        public ActionResult Details(string key)
        {
            SaudoContext context = SaudoContext.Default();

            Saudo saudo = context.Saudos.Where((s) => (s.RowKey == key)).FirstOrDefault();
            IEnumerable<Comment> comments = context.Comments.Where((c) => (c.PartitionKey == key));

            ViewBag.Comments = comments;

            return View(saudo);
        }

        public ActionResult Comment(string key, string text)
        {
            SaudoLogic logic = new SaudoLogic();
            logic.CommentSaudo(key, text);
            return Redirect("/Home/Details?key=" + key);
        }

        [Authorize]
        public ActionResult SendSaudo(string receiver, string text)
        {
            SaudoLogic logic = new SaudoLogic();
            logic.SendSaudo(User.Identity.Name, receiver, text);
            return Redirect("/Home/Index");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your quintessential app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your quintessential contact page.";

            return View();
        }
    }
}
